package server

import (
	"io"
	"log"
	"net/http"
	"strings"
)

type CacheHandler struct {
	*HttpServer
}

func (c *CacheHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 处理请求path
	key := strings.Split(r.URL.EscapedPath(), "/")[2]
	if len(key) == 0 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// 根据request type及path具体处理动作
	method := r.Method
	switch method {
	case http.MethodGet:
		content, err := c.Get(key)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		if len(content) == 0 {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		_, err = w.Write(content)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

	case http.MethodPut:
		content, _ := io.ReadAll(r.Body)
		if len(content) == 0 {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		err := c.Set(key, content)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

	case http.MethodDelete:
		err := c.Delete(key)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
}

func (s *HttpServer) cacheHandler() http.Handler {
	return &CacheHandler{s}
}
